<!-- 设备巡检-巡检模板-新增/编辑/复制页面 -->
<template>
  <div class="add-equip-detail">
    <div class="add-equip-content">
      <px-button style="margin-top: 16px; margin-bottom: 16px" type="primary" icon="ArrowLeft" @click="cancelMainPage">返回</px-button>
      <px-scrollbar class="add-equip-body">
        <!-- 基本信息 -->
        <BaseInfoForm
          ref="baseInfoFormRef"
          v-model:baseInfo="baseInfo"
          :defaultData="defaultData.baseInfo"
          :temCode="temCode"
          style="margin-top: 0"
          @clearEquip="clearEquip"
        />
        <!-- 巡检规则 -->
        <transition name="slide-fade">
          <!-- 设备巡检 -->
          <CheckRuleContentForm
            v-show="baseInfo?.inspectContentType === 1"
            ref="checkRuleContentFormRefEq"
            v-model:ruleContent="eqpRuleContent"
            :baseInfoFormValue="baseInfo"
            :defaultData="defaultData.eqpRuleContent"
          />
        </transition>
        <transition name="slide-fade">
          <!-- 环境巡检 -->
          <CheckRuleContentForm
            v-show="baseInfo?.inspectContentType === 2"
            ref="checkRuleContentFormRefEnv"
            v-model:ruleContent="envRuleContent"
            :baseInfoFormValue="baseInfo"
            :defaultData="defaultData.envRuleContent"
          />
        </transition>
      </px-scrollbar>
    </div>
    <div class="info-form-btns">
      <px-button @click="cancelMainPage">取消</px-button>
      <px-button type="primary" :disabled="saveContentDisabled" @click="handleSubmit">保存</px-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { reactive, toRefs, onMounted, computed } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import BaseInfoForm from "./components/BaseInfoForm.vue";
import CheckRuleContentForm from "./components/CheckRuleContentForm.vue";
import { getInspectTemplate } from "@/api/equip/inspectTemplate";
import { saveInspectTemplate, updateInspectTemplate, getTemCode } from "@/api/equip/inspectTemplate";
import { useRoute, useRouter } from "vue-router";
import { useAction } from "./hooks";
const router = useRouter();
const route = useRoute();
const actions = useAction();
// 页面本身的值
const state = reactive<any>({
  defaultData: {},
  temCode: "",
  // 基础信息
  baseInfo: {},
  baseInfoFormRef: null, // 基础信息ref
  checkRuleContentFormRefEq: null,
  checkRuleContentFormRefEnv: null,
  eqpRuleContent: [],
  envRuleContent: []
});
const { defaultData, baseInfo, temCode, baseInfoFormRef, checkRuleContentFormRefEq, checkRuleContentFormRefEnv, eqpRuleContent, envRuleContent } =
  toRefs(state);

const getDetail = async () => {
  const {
    query: { id },
    path
  } = route;
  if (id) {
    const dataDetail = await getInspectTemplate(id);
    const { templateContentDTOList, inspectTemplateAreaDTOList, temCode: code, ...others } = dataDetail;
    const inspectArea = inspectTemplateAreaDTOList.map(item => item.inspectArea);
    if (path === "/all/equip/inspect/template/edit") {
      // 1、编辑页面
      defaultData.value.baseInfo = { ...others, inspectArea };
      temCode.value = code;
    }
    if (path === "/all/equip/inspect/template/copy") {
      // 2、复制页面
      const data = await getTemCode();
      defaultData.value.baseInfo = { ...others, temCode: data, inspectArea };
    }
    if (others.inspectContentType === 1) {
      defaultData.value.eqpRuleContent = templateContentDTOList;
    }
    if (others.inspectContentType === 2) {
      defaultData.value.envRuleContent = templateContentDTOList;
    }
  }
  if (path === "/all/equip/inspect/template/add") {
    // 3、新增页面
    const data = await getTemCode();
    temCode.value = data;
  }
};
onMounted(() => {
  getDetail();
});
// 基本信息条件改变，清空巡检规则设备
const clearEquip = () => {
  checkRuleContentFormRefEq.value.clearEquip();
  checkRuleContentFormRefEnv.value.clearEquip();
};
// 当前选中巡检内容的总表格，可以遍历
const templateContentDTOList = computed(() => {
  if (baseInfo.value?.inspectContentType === 1) {
    // 巡检内容是设备巡检
    return eqpRuleContent.value;
  }
  if (baseInfo.value?.inspectContentType === 2) {
    // 巡检内容是环境巡检
    return envRuleContent.value;
  }
  return [];
});
// 禁用条件
const saveContentDisabled = computed(() => {
  if (templateContentDTOList.value.length === 0) return true;
  if (
    templateContentDTOList.value.every(item => {
      return item.isTableEdit === "view";
    })
  ) {
    return false;
  }
  return true;
});
// 转换巡检规则提交信息
const transformCheckRuleContentList = templateContentDTOList => {
  // 添加sort排序
  const newCheckRuleContentList = templateContentDTOList.map((item, index) => {
    const newItem = {
      ...item,
      sort: index
    };
    if (item.inspectItemType === 1) {
      newItem.meterReadingContentItemDTOList = item.contentItemDTOList;
    }
    if (item.inspectItemType === 2) {
      newItem.judgeContentItemDTOList = item.contentItemDTOList;
    }
    return newItem;
  });
  // 获取全部抄表类
  const meterReadingContentDTOList = newCheckRuleContentList.filter(item => item.inspectItemType === 1);
  // 获取全部判断类
  const judgeContentDTOList = newCheckRuleContentList.filter(item => item.inspectItemType === 2);
  return {
    meterReadingContentDTOList,
    judgeContentDTOList
  };
};
// 保存基础信息、
const handleSubmit = async () => {
  // 1、校验基本信息表单
  const baseInfoFlag = await baseInfoFormRef.value.form.validate();
  // 2、校验巡检项表单
  const checkRuleContentFormRef = baseInfo.value.inspectContentType === 1 ? checkRuleContentFormRefEq : checkRuleContentFormRefEnv;

  const checkRuleContentFlag = await checkRuleContentFormRef.value.form.validate();
  if (baseInfoFlag && checkRuleContentFlag) {
    const { path } = route;
    const newCheckRuleContentList = transformCheckRuleContentList(templateContentDTOList.value);
    const { id, inspectArea, ...others } = baseInfo.value;
    let new_inspectArea = "";
    new_inspectArea = inspectArea || undefined;
    // 新增与复制页面提交
    if (path === "/all/equip/inspect/template/add" || path === "/all/equip/inspect/template/copy") {
      await saveInspectTemplate({ ...others, ...newCheckRuleContentList, inspectAreaList: new_inspectArea });
    }
    // 编辑页面提交
    if (path === "/all/equip/inspect/template/edit") {
      await updateInspectTemplate({ id, ...baseInfo.value, ...newCheckRuleContentList, inspectAreaList: new_inspectArea });
    }
    PxMessage.success("保存成功");
    router.push("/all/equip/inspect/template");
  } else {
    PxMessage.error("表单校验未通过，请检查");
  }
};
// 返回主页面
const cancelMainPage = () => {
  PxMessageBox.confirm("确认退出页面？退出后内容不会保存", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      resetManagePage();
    })
    .catch(() => {});
};
// 清空全部数据
const resetManagePage = () => {
  baseInfoFormRef.value.form?.resetFields();
  checkRuleContentFormRefEq.value.form?.resetFields();
  checkRuleContentFormRefEnv.value.form?.resetFields();
  actions.back();
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-enter-from {
  opacity: 0;
  transform: translateX(20px);
}

.add-equip-detail {
  .add-equip-content {
    height: calc(100vh - 200px);

    .px-steps--simple {
      padding: 13px 22%;
    }
  }

  .add-equip-body {
    height: calc(100vh - 278px);
  }
}
</style>
